{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Data Manipulation\n",
    "\n",
    ":label:`sec_ndarray`\n",
    "\n",
    "\n",
    "In order to get anything done, we need some way to store and manipulate data. \n",
    "Generally, there are two important things we need to do with data: \n",
    "(i) acquire them; and (ii) process them once they are inside the computer. \n",
    "There is no point in acquiring data without some way to store it, \n",
    "so let us get our hands dirty first by playing with synthetic data. \n",
    "To start, we introduce the $n$-dimensional array (`ndarray`), \n",
    "MXNet's primary tool for storing and transforming data.\n",
    "In MXNet, `ndarray` is a class and we call any instance \"an `ndarray`\".\n",
    "\n",
    "If you have worked with NumPy, the most widely-used \n",
    "scientific computing package in Python, \n",
    "then you will find this section familiar.\n",
    "That's by design. We designed MXNet's `ndarray` to be \n",
    "an extension to NumPy's `ndarray` with a few killer features.\n",
    "First, MXNet's `ndarray` supports asynchronous computation \n",
    "on CPU, GPU, and distributed cloud architectures, \n",
    "whereas NumPy only supports CPU computation. \n",
    "Second, MXNet's `ndarray` supports automatic differentiation. \n",
    "These properties make MXNet's `ndarray` suitable for deep learning.\n",
    "Throughout the book, when we say `ndarray`, \n",
    "we are referring to MXNet's `ndarray` unless otherwise stated.\n",
    "\n",
    "\n",
    "\n",
    "## Getting Started\n",
    "\n",
    "In this section, we aim to get you up and running,\n",
    "equipping you with the basic math and numerical computing tools\n",
    "that you will build on as you progress through the book. \n",
    "Do not worry if you struggle to grok some of \n",
    "the mathematical concepts or library functions. \n",
    "The following sections will revisit this material \n",
    "in the context of practical examples and it will sink. \n",
    "On the other hand, if you already have some background \n",
    "and want to go deeper into the mathematical content, just skip this section.\n",
    "\n",
    "To start, we import the `api`, `mxnet-engine` and \n",
    "`mxnet-native-auto` modules from Deep Java Library on maven. \n",
    "Here, the `api` module includes all high level Java APIs that will be used for data processing, training and inference. The `mxnet-engine` includes the implementation of those high level APIs using Apache MXnet framework.\n",
    "The `mxnet-native-auto` module contains the MXNet native libraries with basic operators and functions implemented in C++."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "1"
    }
   },
   "outputs": [],
   "source": [
    "%maven ai.djl:api:0.6.0\n",
    "%maven org.slf4j:slf4j-api:1.7.26\n",
    "%maven org.slf4j:slf4j-simple:1.7.26\n",
    "\n",
    "// See https://github.com/awslabs/djl/blob/master/mxnet/mxnet-engine/README.md\n",
    "// for more MXNet library selection options\n",
    "%maven ai.djl.mxnet:mxnet-engine:0.6.0\n",
    "%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "1"
    }
   },
   "outputs": [],
   "source": [
    "import ai.djl.Device;\n",
    "import ai.djl.ndarray.*;\n",
    "import ai.djl.ndarray.types.*;\n",
    "import ai.djl.ndarray.index.*;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An `ndarray` represents a (possibly multi-dimensional) array of numerical values.\n",
    "With one axis, an `ndarray` corresponds (in math) to a *vector*. \n",
    "With two axes, an `ndarray` corresponds to a *matrix*. \n",
    "Arrays with more than two axes do not have special \n",
    "mathematical names---we simply call them *tensors*.\n",
    "\n",
    "To start, we can use `arange` to create a row vector `x` \n",
    "containing the first $12$ integers starting with $0$, \n",
    "though they are created as floats by default.\n",
    "Each of the values in an `ndarray` is called an *element* of the `ndarray`.\n",
    "For instance, there are $12$ elements in the `ndarray` `x`.\n",
    "Unless otherwise specified, a new `ndarray` \n",
    "will be stored in main memory and designated for CPU-based computation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (12) cpu() int32\n",
       "[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]\n"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "var x = manager.arange(12);\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we are using a [`NDManager`](https://javadoc.io/doc/ai.djl/api/latest/ai/djl/ndarray/NDManager.html) to create the `ndarray` x. `NDManager` implements the [AutoClosable](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html) interface and manages the life cycles of the `ndarray`s it created. This is needed to help manage native memory consumption that Java Garbage Collector does not have control of. We usually wrap NDManager with try blocks so all `ndarray`s will be closed in time. To know more about memory management, read DJL's [documentation](https://github.com/awslabs/djl/blob/master/docs/development/memory_management.md)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "try(NDManager manager = NDManager.newBaseManager()){\n",
    "    NDArray x = manager.arange(12);\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can access an `ndarray`'s *shape* (the length along each axis)\n",
    "by inspecting its `shape` property."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(12)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.getShape()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we just want to know the total number of elements in an `ndarray`,\n",
    "i.e., the product of all of the shape elements, \n",
    "we can inspect its `size` property. \n",
    "Because we are dealing with a vector here, \n",
    "the single element of its `shape` is identical to its `size`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "4"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.size()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To change the shape of an `ndarray` without altering \n",
    "either the number of elements or their values,\n",
    "we can invoke the `reshape` function.\n",
    "For example, we can transform our `ndarray`, `x`, \n",
    "from a row vector with shape ($12$,) to a matrix with shape ($3$, $4$).\n",
    "This new `ndarray` contains the exact same values, \n",
    "but views them as a matrix organized as $3$ rows and $4$ columns. \n",
    "To reiterate, although the shape has changed, \n",
    "the elements in `x` have not. \n",
    "Note that the `size` is unaltered by reshaping."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() int32\n",
       "[[ 0,  1,  2,  3],\n",
       " [ 4,  5,  6,  7],\n",
       " [ 8,  9, 10, 11],\n",
       "]\n"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = x.reshape(3, 4);\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reshaping by manually specifying every dimension is unnecessary. \n",
    "If our target shape is a matrix with shape (height, width),\n",
    "then after we know the width, the height is given implicitly.\n",
    "Why should we have to perform the division ourselves? \n",
    "In the example above, to get a matrix with $3$ rows, \n",
    "we specified both that it should have $3$ rows and $4$ columns. \n",
    "Fortunately, `ndarray` can automatically work out one dimension given the rest. \n",
    "We invoke this capability by placing `-1` for the dimension\n",
    "that we would like `ndarray` to automatically infer. \n",
    "In our case, instead of calling `x.reshape(3, 4)`, \n",
    "we could have equivalently called `x.reshape(-1, 4)` or `x.reshape(3, -1)`.\n",
    "\n",
    "Passing `create` method with only `Shape` will grab a chunk of memory and hands us back a matrix \n",
    "without bothering to change the value of any of its entries. \n",
    "This is remarkably efficient but we must be careful because \n",
    "the entries might take arbitrary values, including very big ones!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "6"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[ 0.00000000e+00, -1.58456325e+29,  0.00000000e+00, -1.58456325e+29],\n",
       " [ 1.84361280e+25,  4.80083749e-29,  1.83738255e-40,  9.18411014e-41],\n",
       " [ 8.40779079e-45,  1.83673795e-40,  7.34693778e-40,  1.74487583e-39],\n",
       "]\n"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.create(new Shape(3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Typically, we will want our matrices initialized \n",
    "either with zeros, ones, some other constants, \n",
    "or numbers randomly sampled from a specific distribution.\n",
    "We can create an `ndarray` representing a tensor with all elements \n",
    "set to $0$ and a shape of ($2$, $3$, $4$) as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (2, 3, 4) cpu() float32\n",
       "[[[0., 0., 0., 0.],\n",
       "  [0., 0., 0., 0.],\n",
       "  [0., 0., 0., 0.],\n",
       " ],\n",
       " [[0., 0., 0., 0.],\n",
       "  [0., 0., 0., 0.],\n",
       "  [0., 0., 0., 0.],\n",
       " ],\n",
       "]\n"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.zeros(new Shape(2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, we can create tensors with each element set to 1 as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "8"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (2, 3, 4) cpu() float32\n",
       "[[[1., 1., 1., 1.],\n",
       "  [1., 1., 1., 1.],\n",
       "  [1., 1., 1., 1.],\n",
       " ],\n",
       " [[1., 1., 1., 1.],\n",
       "  [1., 1., 1., 1.],\n",
       "  [1., 1., 1., 1.],\n",
       " ],\n",
       "]\n"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.ones(new Shape(2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Often, we want to randomly sample the values\n",
    "for each element in an `ndarray`\n",
    "from some probability distribution.\n",
    "For example, when we construct arrays to serve\n",
    "as parameters in a neural network, we will\n",
    "typically initialize their values randomly.\n",
    "The following snippet creates an `ndarray` with shape ($3$, $4$).\n",
    "Each of its elements is randomly sampled\n",
    "from a standard Gaussian (normal) distribution\n",
    "with a mean of $0$ and a standard deviation of $1$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "10"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[ 1.1631,  2.2122,  0.4838,  0.774 ],\n",
       " [ 0.2996,  1.0434,  0.153 ,  1.1839],\n",
       " [-1.1688,  1.8917,  1.5581, -1.2347],\n",
       "]\n"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.randomNormal(0f, 1f, new Shape(3, 4), DataType.FLOAT32, Device.defaultDevice())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also just pass the shape and it will use default values for mean and standard deviation (0 and 1)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[-0.5459, -1.771 , -2.3556, -0.4514],\n",
       " [ 0.5414,  0.5794,  2.6785, -1.8561],\n",
       " [ 1.2546, -1.9769, -0.5488, -0.208 ],\n",
       "]\n"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.randomNormal(new Shape(3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also specify the exact values for each element in the desired `ndarray`\n",
    "by supplying an array containing the numerical values and the desired shape."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[2., 1., 4., 3.],\n",
       " [1., 2., 3., 4.],\n",
       " [4., 3., 2., 1.],\n",
       "]\n"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "manager.create(new float[]{2, 1, 4, 3, 1, 2, 3, 4, 4, 3, 2, 1}, new Shape(3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Operations\n",
    "\n",
    "This book is not about software engineering.\n",
    "Our interests are not limited to simply \n",
    "reading and writing data from/to arrays.\n",
    "We want to perform mathematical operations on those arrays.\n",
    "Some of the simplest and most useful operations \n",
    "are the *elementwise* operations. \n",
    "These apply a standard scalar operation \n",
    "to each element of an array.\n",
    "For functions that take two arrays as inputs,\n",
    "elementwise operations apply some standard binary operator \n",
    "on each pair of corresponding elements from the two arrays. \n",
    "We can create an elementwise function from any function \n",
    "that maps from a scalar to a scalar. \n",
    "\n",
    "In mathematical notation, we would denote such\n",
    "a *unary* scalar operator (taking one input)\n",
    "by the signature $f: \\mathbb{R} \\rightarrow \\mathbb{R}$.\n",
    "This just means that the function is mapping\n",
    "from any real number ($\\mathbb{R}$) onto another.\n",
    "Likewise, we denote a *binary* scalar operator\n",
    "(taking two real inputs, and yielding one output)\n",
    "by the signature $f: \\mathbb{R}, \\mathbb{R} \\rightarrow \\mathbb{R}$.\n",
    "Given any two vectors $\\mathbf{u}$ and $\\mathbf{v}$ *of the same shape*,\n",
    "and a binary operator $f$, we can produce a vector\n",
    "$\\mathbf{c} = F(\\mathbf{u},\\mathbf{v})$\n",
    "by setting $c_i \\gets f(u_i, v_i)$ for all $i$,\n",
    "where $c_i, u_i$, and $v_i$ are the $i^\\mathrm{th}$ elements\n",
    "of vectors $\\mathbf{c}, \\mathbf{u}$, and $\\mathbf{v}$.\n",
    "Here, we produced the vector-valued\n",
    "$F: \\mathbb{R}^d, \\mathbb{R}^d \\rightarrow \\mathbb{R}^d$\n",
    "by *lifting* the scalar function to an elementwise vector operation.\n",
    "\n",
    "In DJL, the common standard arithmetic operators\n",
    "(`+`, `-`, `*`, `/`, and `**`)\n",
    "have all been *lifted* to elementwise operations \n",
    "for any identically-shaped tensors of arbitrary shape. \n",
    "We can call elementwise operations on any two tensors of the same shape.\n",
    "In the following example, we use commas to formulate a $5$-element tuple,\n",
    "where each element is the result of an elementwise operation. Note: you need to use `add`, `sub`, `mul`, `div`, and `pow` as Java does not support overloading of these operators."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[ 3.,  4.,  6., 10.]\n"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "var x = manager.create(new float[]{1f, 2f, 4f, 8f});\n",
    "var y = manager.create(new float[]{2f, 2f, 2f, 2f});\n",
    "x.add(y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[-1.,  0.,  2.,  6.]\n"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.sub(y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[ 2.,  4.,  8., 16.]\n"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.mul(y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[0.5, 1. , 2. , 4. ]\n"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.div(y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[ 1.,  4., 16., 64.]\n"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.pow(y);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many more operations can be applied elementwise,\n",
    "including unary operators like exponentiation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "12"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (4) cpu() float32\n",
       "[ 2.71828175e+00,  7.38905621e+00,  5.45981483e+01,  2.98095801e+03]\n"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.exp()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to elementwise computations, \n",
    "we can also perform linear algebra operations, \n",
    "including vector dot products and matrix multiplication.\n",
    "We will explain the crucial bits of linear algebra \n",
    "(with no assumed prior knowledge) in :numref:`sec_linear-algebra`.\n",
    "\n",
    "We can also *concatenate* multiple `ndarray`s together,\n",
    "stacking them end-to-end to form a larger `ndarray`. \n",
    "We just need to provide a list of `ndarray`s \n",
    "and tell the system along which axis to concatenate. \n",
    "The example below shows what happens when we concatenate \n",
    "two matrices along rows (axis $0$, the first element of the shape)\n",
    "vs. columns (axis $1$, the second element of the shape).\n",
    "We can see that the first output `ndarray`'s axis-$0$ length ($6$)\n",
    "is the sum of the two input `ndarray`s' axis-$0$ lengths ($3 + 3$);\n",
    "while the second output `ndarray`'s axis-$1$ length ($8$)\n",
    "is the sum of the two input `ndarray`s' axis-$1$ lengths ($4 + 4$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "14"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (6, 4) cpu() float32\n",
       "[[ 0.,  1.,  2.,  3.],\n",
       " [ 4.,  5.,  6.,  7.],\n",
       " [ 8.,  9., 10., 11.],\n",
       " [ 2.,  1.,  4.,  3.],\n",
       " [ 1.,  2.,  3.,  4.],\n",
       " [ 4.,  3.,  2.,  1.],\n",
       "]\n"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = manager.arange(12f).reshape(3, 4);\n",
    "y = manager.create(new float[]{2, 1, 4, 3, 1, 2, 3, 4, 4, 3, 2, 1}, new Shape(3, 4));\n",
    "x.concat(y) // default axis = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "14"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 8) cpu() float32\n",
       "[[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],\n",
       " [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],\n",
       " [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.],\n",
       "]\n"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.concat(y, 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes, we want to construct a binary `ndarray` via *logical statements*. \n",
    "Take `x.eq(y)` as an example. \n",
    "For each position, if `x` and `y` are equal at that position,\n",
    "the corresponding entry in the new `ndarray` takes a value of $1$,\n",
    "meaning that the logical statement `x.eq(y)` is true at that position;\n",
    "otherwise that position takes $0$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "15"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() boolean\n",
       "[[false,  true, false,  true],\n",
       " [false, false, false, false],\n",
       " [false, false, false, false],\n",
       "]\n"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.eq(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Summing all the elements in the `ndarray` yields an `ndarray` with only one element."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "16"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: () cpu() float32\n",
       "66.\n"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For stylistic convenience, we can write `x.sum()` as `np.sum(x)`.\n",
    "\n",
    "## Broadcasting Mechanism\n",
    "\n",
    "In the above section, we saw how to perform elementwise operations\n",
    "on two `ndarray`s of the same shape. Under certain conditions, \n",
    "even when shapes differ, we can still perform elementwise operations\n",
    "by invoking the *broadcasting mechanism*.\n",
    "This mechanism works in the following way:\n",
    "First, expand one or both arrays\n",
    "by copying elements appropriately \n",
    "so that after this transformation, \n",
    "the two `ndarray`s have the same shape.\n",
    "Second, carry out the elementwise operations\n",
    "on the resulting arrays.\n",
    "\n",
    "In most cases, we broadcast along an axis where an array\n",
    "initially only has length $1$, such as in the following example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "17"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 1) cpu() float32\n",
       "[[0.],\n",
       " [1.],\n",
       " [2.],\n",
       "]\n"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "var a = manager.arange(3f).reshape(3, 1);\n",
    "var b = manager.arange(2f).reshape(1, 2);\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "17"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (1, 2) cpu() float32\n",
       "[[0., 1.],\n",
       "]\n"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since `a` and `b` are $3\\times1$ and $1\\times2$ matrices respectively, \n",
    "their shapes do not match up if we want to add them. \n",
    "We *broadcast* the entries of both matrices into a larger $3\\times2$ matrix as follows: \n",
    "for matrix `a` it replicates the columns\n",
    "and for matrix `b` it replicates the rows\n",
    "before adding up both elementwise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "18"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 2) cpu() float32\n",
       "[[0., 1.],\n",
       " [1., 2.],\n",
       " [2., 3.],\n",
       "]\n"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.add(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Indexing and Slicing\n",
    "\n",
    "DJL use the same syntax as Numpy in Python for indexing and slicing. Just as in any other Python array, elements in an `ndarray` can be accessed by index. \n",
    "As in any Python array, the first element has index $0$\n",
    "and ranges are specified to include the first but *before* the last element. \n",
    "As in standard Python lists, we can access elements \n",
    "according to their relative position to the end of the list \n",
    "by using negative indices.\n",
    "\n",
    "Thus, `[-1]` selects the last element and `[1:3]` \n",
    "selects the second and the third elements as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "19"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (2, 4) cpu() float32\n",
       "[[0., 1., 2., 3.],\n",
       " [4., 5., 6., 7.],\n",
       "]\n"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.get(\":-1\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "19"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (2, 4) cpu() float32\n",
       "[[ 4.,  5.,  6.,  7.],\n",
       " [ 8.,  9., 10., 11.],\n",
       "]\n"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.get(\"1:3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Beyond reading, we can also write elements of a matrix by specifying indices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "20"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[ 0.,  1.,  2.,  3.],\n",
       " [ 4.,  5.,  9.,  7.],\n",
       " [ 8.,  9., 10., 11.],\n",
       "]\n"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.set(new NDIndex(\"1, 2\"), 9);\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we want to assign multiple elements the same value, \n",
    "we simply index all of them and then assign them the value. \n",
    "For instance, `[0:2, :]` accesses the first and second rows,\n",
    "where `:` takes all the elements along axis $1$ (column).\n",
    "While we discussed indexing for matrices, \n",
    "this obviously also works for vectors \n",
    "and for tensors of more than $2$ dimensions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "21"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ND: (3, 4) cpu() float32\n",
       "[[12., 12., 12., 12.],\n",
       " [12., 12., 12., 12.],\n",
       " [ 8.,  9., 10., 11.],\n",
       "]\n"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.set(new NDIndex(\"0:2, :\"), 12);\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Saving Memory\n",
    "\n",
    "Running operations can cause new memory to be\n",
    "allocated to host results. \n",
    "For example, if we write `y = x.add(y)`, \n",
    "we will dereference the `ndarray` that `y` used to point to \n",
    "and instead point `y` at the newly allocated memory. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This might be undesirable for two reasons.\n",
    "First, we do not want to run around \n",
    "allocating memory unnecessarily all the time. \n",
    "In machine learning, we might have \n",
    "hundreds of megabytes of parameters \n",
    "and update all of them multiple times per second. \n",
    "Typically, we will want to perform these updates *in place*. \n",
    "Second, we might point at the same parameters from multiple variables. \n",
    "If we do not update in place, other references will still point to\n",
    "the old memory location, making it possible for parts of our code\n",
    "to inadvertently reference stale parameters.\n",
    "\n",
    "Fortunately, performing in-place operations in DJL is easy. \n",
    "We can assign the result of an operation \n",
    "to a previously allocated array using inplace operators like `addi`, `subi`, `muli`, and `divi`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "23"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "true"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "var original = manager.zeros(y.getShape());\n",
    "var actual = original.addi(x);\n",
    "original == actual"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "* DJL's `ndarray` is an extension to NumPy's `ndarray` \n",
    "  with a few killer advantages that make it suitable for deep learning.\n",
    "* DJL's `ndarray` provides a variety of functionalities including \n",
    "  basic mathematics operations, broadcasting, indexing, slicing, \n",
    "  memory saving, and conversion to other Python objects.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Run the code in this section. Change the conditional statement `x.eq(y)` in this section to `x.lt(y)` (less than) or `x.gt(y)` (greater than), and then see what kind of `ndarray` you can get.\n",
    "1. Replace the two `ndarray`s that operate by element in the broadcasting mechanism with other shapes, e.g., three dimensional tensors. Is the result the same as expected?\n",
    "\n",
    "\n",
    "## [Discussions](https://discuss.mxnet.io/t/2316)\n",
    "\n",
    "![](../img/qr_ndarray.svg)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "12.0.2+10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
